<template>
    <div>
        <!-- 搜索 -->
        <el-form :inline="true">
            <el-form-item label="姓名">
                <el-input v-model="queryInfo.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="queryInfo.phone" placeholder="请输入电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryInfo.status" placeholder="全部" clearable>
                    <el-option label="启用" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="loadUsers(true)">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="danger" @click="removeMultiple">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="userList" border stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" />
            <el-table-column type="index" label="序号" width="55" />
            <el-table-column prop="name" label="姓名" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column prop="address" label="地址" />
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" @change="modifyStatus(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="removeById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 30, 50]" :page-size="queryInfo.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>

        <!-- 添加的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="addForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="addForm.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑的对话框 -->
        <el-dialog title="编辑用户" :visible.sync="editDialogVisible">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item label="用户id" prop="id">
                    <el-input v-model="editForm.id" readonly></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="editForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="editForm.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>

export default {
    data() {
        return {
            // 用户列表
            userList: [],
            // 总条数
            total: 0,
            // 查询条件
            queryInfo: {
                pageNum: 1, // 页码
                pageSize: 5, // 页大小
                name: '',
                phone: '',
                status: null
            },
            // 添加对话框的显示和隐藏
            addDialogVisible: false,
            // 添加用户的表单数据
            addForm: {},
            // 添加用户的表单验证规则
            addFormRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ],

            },
            // 选中的项列表
            multipleSelection: [],
            // 编辑对话框的显示和隐藏
            editDialogVisible: false,
            // 编辑用户的表单数据
            editForm: {},
            // 编辑用户的表单验证规则
            editFormRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话', trigger: 'blur' },
                    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' },
                ],

            },

        }
    },
    created() {
        this.loadUsers()
    },
    methods: {
        // 加载用户列表
        async loadUsers(flag) {
            // 如果flag为true，说明是查询操作，从第1页开始
            if (flag) {
                this.queryInfo.pageNum = 1
            }

            const { data: res } = await this.$http.get('user/queryByPage', {
                params: this.queryInfo
            })
            if (res.status != 200) {
                alert('获取用户列表失败')
                return
            }
            this.total = res.data.total
            this.userList = res.data.list
            this.userList.forEach(item => {
                item.status = item.status == 0 ? true : false
            })
        },
        // 修改用户状态
        async modifyStatus(user) {
            console.log(user)

            const { data: res } = await this.$http.put(`user/modifyStatus/${user.id}/${user.status ? 0 : 1}`)
            if (res.status != 200) {
                this.$message.error('修改状态失败！')
                return
            }
            this.$message.success('修改状态成功！')
        },
        // 监听页大小的改变
        handleSizeChange(val) {
            this.queryInfo.pageSize = val
            this.loadUsers()
        },
        // 监听页码的改变
        handleCurrentChange(val) {
            // 修改查询条件中的页码
            this.queryInfo.pageNum = val
            // 重新加载用户列表
            this.loadUsers()
        },
        // 根据id删除
        removeById(id) {
            this.$confirm('确定要删除吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`user/remove/${id}`)
                if (res.status != 200) {
                    this.$message.error('删除失败！')
                    return
                }
                // 提示消息
                this.$message.success('删除成功！');
                // 重载数据
                this.loadUsers().then(() => {
                    if (this.userList.length == 0 && this.queryInfo.pageNum > 1) {
                        this.queryInfo.pageNum--
                        this.loadUsers()
                    }
                })
            }).catch(() => {
                this.$message.info('取消删除');
            });
        },
        // 添加用户
        addUser() {
            // 先进行表单校验
            this.$refs.addFormRef.validate(async (valid) => {
                if (!valid) {
                    return
                }

                // 表单校验通过，向服务器发送请求，添加用户
                const { data: res } = await this.$http.post('user/add', this.addForm)
                if (res.status != 200) {
                    this.$message.error('添加失败！')
                    return
                }
                // 提示添加成功消息
                this.$message.success('添加成功！')
                // 关闭对话框
                this.addDialogVisible = false
                // 重新加载用户
                this.loadUsers()
            });
        },
        // 监听添加对话框的关闭事件
        addDialogClosed() {
            // 清空表单数据和校验结果
            this.$refs.addFormRef.resetFields()
        },
        // 监听复选框的改变
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        // 批量删除
        removeMultiple() {
            this.$confirm('确定要删除吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const ids = this.multipleSelection.map(item => item.id)
                const { data: res } = await this.$http.delete(`user/removeBatch`, {
                    data: ids
                })
                if (res.status != 200) {
                    this.$message.error('删除失败！')
                    return
                }
                // 提示消息
                this.$message.success('删除成功！');
                // 重载数据
                this.loadUsers().then(() => {
                    if (this.userList.length == 0 && this.queryInfo.pageNum > 1) {
                        this.queryInfo.pageNum--
                        this.loadUsers()
                    }
                })
            }).catch(() => {
                this.$message.info('取消删除');
            });
        },
        // 显示编辑对话框
        async showEditDialog(id) {
            const { data: res } = await this.$http.get(`user/query/${id}`)
            if (res.status != 200) {
                this.$message.error('获取用户信息失败！')
                return
            }
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 修改用户
        editUser() {
            // 先进行表单校验
            this.$refs.editFormRef.validate(async (valid) => {
                if (!valid) {
                    return
                }

                // 表单校验通过，向服务器发送请求，添加用户
                const { data: res } = await this.$http.put('user/modify', this.editForm)
                if (res.status != 200) {
                    this.$message.error('修改失败！')
                    return
                }
                // 提示添加成功消息
                this.$message.success('修改成功！')
                // 关闭对话框
                this.editDialogVisible = false
                // 重新加载用户
                this.loadUsers()
            });
        }
    }
}
</script>

<style scoped>
.el-pagination {
    text-align: center;
}
</style>